<?php

include_once($ROOT . "base.inc.php");

class PageController extends BaseController {
  var $user;
  var $userRoles;

  var $users;
  var $roles;

  function PageController() {
	parent::__construct();

	$this->title="Users";
	$this->section="admin";

	$action = $this->getParameter("action");
	$this->user = new User();
	$this->userRoles = array();

	switch (strtoupper($action))
	{
		case "SAVE" :
			  $this->parseForm();
			  if (!$this->validate()) break;

			  if (!UserLogic::save($this->user) && $this->user->id == 0)
			  {
			  	$this->addError("Could not save user");
			  	break;
			  }

			  if (!UserLogic::saveRoles($this->user->id, $this->userRoles))
			  {
			  	 $this->addError("Could not save roles");
			  }

			  $this->addMessage("Saved");
			  break;

		case "LOAD" :
			  $id = $this->getParameter("id");
	  		  $this->user = UserLogic::load($id);
	  		  $this->userRoles = UserLogic::loadRoles($id);
	  		  $this->addMessage("Loaded $id");
	  		  break;
	  	case "CANCEL" :
	  		  HtmlUtil::redirectToPage("index");

	}


	$this->users = UserLogic::findAll();
	$this->roles = UserUtil::getAvailableRoles();

  }

  function parseForm() {
	$this->user->readForm();

	$this->userRoles = $this->getParameter("roles");

  }

  function validate() {
  	if ($this->user->username == "")
  		$this->addError("A username is required");
  	if ($this->user->id == 0 && $this->user->password == "")
  		$this->addError("A password is required when createing a new user");
  	if ($this->contact != null && ($this->contact->firstname == ""))
  		$this->addError("A first name is required when creating a new contact");
  	if ($this->address != null && $this->address->state == "" && $this->address-> zip == "")
  		$this->addError("A state or zip is required when creating a new address");
	return (sizeof($this->errs) == 0);
  }

}



?>
